#
#  SMSWindowController.rb
#  BiBoBSMS
#
#  Created by Mikkel Gravgaard on 02/09/08.
#  Copyright (c) 2008 __MyCompanyName__. All rights reserved.
#

require 'osx/cocoa'
include OSX

require 'rubygems'
require 'digest/md5'

class SMSWindowController < OSX::NSWindowController

	ib_outlet :cellphoneField, :passwordField, :loginBtn
	ib_outlet :receiverField, :msgField, :sendBtn, :contactsBtn, :status, :contactsTable

	attr_reader :driver, :cellphoneField, :passwordField, :msgField

	def awakeFromNib

		@queue = NSOperationQueue.new

		path = OSX::NSBundle.mainBundle.resourcePath.fileSystemRepresentation

		ENV['GEM_HOME'] = path + "/third-party/gems"
		gem 'soap4r'
		require 'soap/wsdlDriver'
		
		wsdlUrl =  OSX::NSURL.fileURLWithPath(path + "/bibob.wsdl").absoluteString

		@driver = SOAP::WSDLDriverFactory.new(wsdlUrl).create_rpc_driver
		@contactsTable.setDataSource(self)
		@contactsTable.setDelegate(self)
		
		@contactsTable.setTarget(self)
		@contactsTable.setAction("click:")
	end
  
	def click(id)
		@receiverField.setStringValue(@contacts[id.clickedRow]['Number']) if @contacts
	end
  
	# protocol for NSTableView
	def tableView_shouldEditTableColumn_row(t,c,r)
		false	
	end

	def numberOfRowsInTableView(t)
		@contacts ? @contacts.size : 0
	end
	
	def tableView_objectValueForTableColumn_row(t,c,r)
		@contacts ? "#{@contacts[r]['FirstName']} #{@contacts[r]['LastName']} (#{@contacts[r]['Number']})" : nil
	end
  
	def cellphone
		@cellphoneField.stringValue.to_s.strip
	end
	
	def password
		Digest::MD5.hexdigest(@passwordField.stringValue.to_s.strip)
	end
	
	def receiver
		# replace + with 00, eg. +45 -> 0045
		@receiverField.stringValue.to_s.strip.gsub(/\+/, "00")
	end
	
	def msg
		# NSTextField
		#@msgField.stringValue.to_s.strip;

		# NSTextView
		@msgField.textStorage.string

	end

	def setStats(s)
		@status.setStringValue(s)
	end

	def contacts(sender)
		@contacts = nil
		@contactsTable.reloadData
		setStats "Henter addressebog ..."
		op = LoadContactsOp.new
		op.init(self)
		@queue.addOperation(op)
	end
	ib_action :contacts

	def doContacts(contacts)
		@contacts = contacts
		@contactsTable.reloadData
		setStats "Addressebog hentet"
	end

	def login(sender)
		setStats "Logger ind ..."
		op = LoginOp.new
		op.init(self)
		@queue.addOperation(op)
	end
	ib_action :login

	def doLogin(login,msg)
		if login
			setStats "Logget ind"
			[@cellphoneField,@passwordField,@loginBtn].each do |c|
				c.setEnabled(false)
			end
			[@receiverField,@sendBtn,@contactsBtn].each do |c|
				c.setEnabled(true)
			end
		else
			setStats "Fejl ved login"
			NSRunAlertPanel("Fejl ved login", msg, 'OK', nil, nil)
		end
	end

	def send(sender)
		setStats "Sender besked til #{receiver} ..."
		op = SendMsgOp.new
		op.init(self)
		@queue.addOperation(op)
	end
	
	def doSend(send,msg)
		if send then
			setStats "Besked sendt til #{receiver}"
		else
			setStats "Fejl ved afsendelse"
			NSRunAlertPanel("Fejl ved afsendelse af sms", msg, 'OK', nil, nil)
		end
	end
	ib_action :send
end

class LoginOp < OSX::NSOperation
  
	def init(sender)
		@sender = sender
	end
	
	def main
		response = @sender.driver.Login(:cellphone=>@sender.cellphone,:password=>@sender.password)
		@sender.doLogin(response.loginResult=="",response.loginResult)
	end
end

class LoadContactsOp <OSX::NSOperation
	def init(sender)
		@sender = sender
	end
	
	def main
		response = @sender.driver.GetRemoteContacts(:cellphone=>@sender.cellphone,:password=>@sender.password)
		@sender.doContacts(response.getRemoteContactsResult["Contacts"]["Contact"])
	end
end

class SendMsgOp < OSX::NSOperation
	def init(sender)
		@sender = sender
	end
	
	def main
		response = @sender.driver.SendMessage(:cellphone=>@sender.cellphone, :password=>@sender.password, :smsTo=>[@sender.receiver], :smscontents=>@sender.msg, :fromNumber=>@sender.cellphone)
		@sender.doSend(response.sendMessageResult["ResultCode"].to_i == 0, "#{response.sendMessageResult['ErrorString']} (fejl #{response.sendMessageResult['ResultCode']})")		
	end
end

